<template>
  <div class="page">
    <textarea ref="letters"></textarea>
    <button @click="copyToClipboard('letters')">复制</button>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // loading: false
    }
  },
  created () {
    this.$nextTick(function () {
      this.$refs.letters.value = ''
    })
  },
  methods: {
    // 复制内容到粘贴板
    copyToClipboard (elemRef) {
      let target
      let succeed = false
      if (this.$refs[elemRef]) {
        target = this.$refs[elemRef]
        // 选择内容
        let currentFocus = document.activeElement
        target.focus()
        target.setSelectionRange(0, target.value.length)
        // 复制内容
        try {
          succeed = document.execCommand('copy')
          alert('内容复制成功')
        } catch (e) {
          succeed = false
        }
        // 恢复焦点
        if (currentFocus && typeof currentFocus.focus === 'function') {
          currentFocus.focus()
        }
      }
      return succeed
    }
  }
}
</script>
